/**
 * Copyright (c) 2014, Jason Gardner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package freecake.tenthousand.states;

import freecake.tenthousand.TenThousand;
import freecake.tenthousand.TransitionCallback;
import freecake.tenthousand.util.ScoringUtilities;

import java.util.Timer;
import java.util.TimerTask;

public class CpuTurnState extends AbstractTurnState {

    private final Timer timer = new Timer();

    @Override
    public final boolean handleStateTransition(final TenThousand.GameState newState, TransitionCallback transitionCallback) {
        if (TenThousand.playerTurn == false &&
            (newState == TenThousand.GameState.TurnStart ||
            newState == TenThousand.GameState.AfterHold ||
            newState == TenThousand.GameState.AfterRoll ||
            newState == TenThousand.GameState.AfterStay ||
            newState == TenThousand.GameState.BadHold ||
            newState == TenThousand.GameState.AfterBust)) {
            redraw(newState);
            switch (newState) {
                case TurnStart:
                    rollDice();
                    if (calculateScoreOfRolledDice() == 0) {
                        timer.schedule(new TransitionTask(TenThousand.GameState.AfterBust, transitionCallback), 2000);
                    } else {
                        timer.schedule(new TransitionTask(TenThousand.GameState.AfterRoll, transitionCallback), 2000);
                    }
                    break;
                case AfterRoll:
                    holdAllDicePossible();
                    timer.schedule(new TransitionTask(TenThousand.GameState.AfterHold, transitionCallback), 2000);
                    break;
                case AfterHold:
                    if (canStay()) {
                        applyCurrentScore();
                        timer.schedule(new TransitionTask(TenThousand.GameState.AfterStay, transitionCallback), 1000);
                    } else {
                        rollDice();
                        if (calculateScoreOfRolledDice() == 0) {
                            timer.schedule(new TransitionTask(TenThousand.GameState.AfterBust, transitionCallback), 1000);
                        } else {
                            timer.schedule(new TransitionTask(TenThousand.GameState.AfterRoll, transitionCallback), 1000);
                        }
                    }
                    break;
                case AfterStay:
                case AfterBust:
                    endTurn();
                    timer.schedule(new TransitionTask(TenThousand.GameState.ChangeUser, transitionCallback), 3000);
                    break;
                //case BadHold:  //never should happen with the CPU
            }
            return true;
        }
        return false;
    }

    private final void holdAllDicePossible() {
        ScoringUtilities.ScoringResult result = calculateScore(false, false);
        for (int i=0;i<ScoringUtilities.NUMBER_OF_DICE;i++) {
            if (!heldDice.contains(i)) {
                if (result.scoringDice.contains(userDiceValues[i])) {
                    heldDiceThisRound.add(i);
                    result.scoringDice.remove(result.scoringDice.indexOf(userDiceValues[i]));
                }
            }
        }
    }

    @Override
    protected void printCurrentDice(final TenThousand.GameState newState) {
        System.out.println(formatter.format(userDiceValues, heldDice, heldDiceThisRound));
    }

    @Override
    protected void printStatusBar(final TenThousand.GameState newState) {
        String status = "It's the CPU's turn.";
        if (newState == TenThousand.GameState.AfterStay) {
            status = "CPU scored " + turnScore + " points this round";
        } else if (newState == TenThousand.GameState.AfterBust) {
            status = "CPU busted!";
        }
        System.out.println(status);
    }

    @Override
    protected void printFooter(final TenThousand.GameState newState) {
        System.out.println("----------------------------------------------------------------------");
        String options = "[q] Quit";
        System.out.println(centerOn70Chars(options));
    }

    private final class TransitionTask extends TimerTask {
        private TenThousand.GameState newState;
        private TransitionCallback callback;

        public TransitionTask(TenThousand.GameState newState, TransitionCallback callback) {
            this.newState = newState;
            this.callback = callback;
        }

        public void run() {
            callback.transitionToGameState(newState);
        }
    }

}